package com.generalbackend.common.util;

import com.generalbackend.common.constants.Constants;
import com.generalbackend.common.model.entity.User;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author tim.xie
 * @date 2021/12/21 10:12
 */
@Slf4j
public class ClientUtil {

    private ClientUtil(){}

    private static final ThreadLocal<HttpServletRequest> requestLocal = new ThreadLocal<>();
    private static final ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<>();

    /**
     * 获取客户端ip
     */
    public static String getIpAddr() {
        return getIpAddr(getRequest());
    }

    public static String getIpAddr(HttpServletRequest request) {
        if (request == null ) {
            return null;
        }
        String ip = request.getHeader("x-real-ip");
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        return ip;
    }

    public static HttpServletRequest getRequest() {
        return requestLocal.get();
    }

    public static HttpSession getSession() {
        HttpSession session = null;
        try {
            if (getRequest() == null) {
                return null;
            }
            session = getRequest().getSession();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return session;
    }

    public static void setRequest(HttpServletRequest request) {
        requestLocal.set(request);
    }

    public static HttpServletResponse getResponse() {
        return responseLocal.get();
    }

    public static void setResponse(HttpServletResponse response) {
        responseLocal.set(response);
    }

    public static User getUser() {
        User user = null;
        HttpSession session = getSession();
        if (session == null) {
            return user;
        }
        try {
            user = (User) session.getAttribute(Constants.USER_INFO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return user;
    }

}
